Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
"x is not a function" in js when using class

I am new to JS and especially class in JS. I don't fully understand how classes work. Please help me in the following question. This is a simple page with a button. I want it to run a function (doThis()) after clicking the button. But it gives an error saying the function is not defined.

class Test {
    constructor() {
        this.button = document.getElementById("but1");
        this.button.addEventListener("click", this.butClick);
    }
    butClick() {
        console.log("clicked");
        this.doThis();
    }
    doThis(){
        console.log("Inside doThis")
    }
}
t1 = new Test();
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <button id="but1">Click me</button>
    <script src="test.js"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

this.button.addEventListener("click", this.butClick); should be this.button.addEventListener("click", this.butClick.bind(this));.

Without bind(this), the this inside butClick is just the button element, not the class Test.

about 4 years ago · Juan Pablo Isaza Relatório

0

class Test {
constructor() {
}
butClick() {
    console.log("clicked");
    this.doThis();
}
doThis(){
    console.log("Inside doThis")
  }
}

t1 = new Test();

const button = document.getElementById("but1")
button.addEventListener('click', event => {
event.preventDefault()
// Call doThis method on t1, the instance...
t1.doThis()
})
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <button id="but1">Click me</button>
    <script src="test.js"></script>
</body>
</html>

I have done some short and helpful article on using classes in JS, should help, go to the article here.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda